package com.zbkj.crmeb.bill.service.impl;

import java.math.BigDecimal;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crmeb.core.exception.CrmebException;
import com.zbkj.crmeb.bill.dao.MerFreezeBillDao;
import com.zbkj.crmeb.bill.model.MerFreezeBill;
import com.zbkj.crmeb.bill.service.MerFreezeBillService;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 商户冻结账单表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2021-09-14
 */
@Service
@Slf4j
public class MerFreezeBillServiceImpl extends ServiceImpl<MerFreezeBillDao, MerFreezeBill> implements MerFreezeBillService {

    @Override
    public void updateAmountFrozen(StoreOrderInfo storeOrderInfo, BigDecimal freezeAccount) {
        //修改冻结账单
        MerFreezeBill merFreezeBill = getOne(Wrappers.lambdaQuery(MerFreezeBill.class).eq(MerFreezeBill::getOrderId, storeOrderInfo.getOrderId())
                .eq(MerFreezeBill::getFrozen,0).last("LIMIT 1"));
        if(merFreezeBill == null ){
            return;
        }
        if(merFreezeBill.getAmountFrozen().subtract(freezeAccount).compareTo(BigDecimal.ZERO)<0){
            throw new CrmebException("冻结账单异常,id:"+merFreezeBill.getId());
        }
        merFreezeBill.setAmountFrozen(merFreezeBill.getAmountFrozen().subtract(freezeAccount));
        updateById(merFreezeBill);
    }

    @Override
    public void addFreezeBill(StoreOrder storeOrder, BigDecimal price) {
        //冻结账单记录
        MerFreezeBill merFreezeBill = new MerFreezeBill();
        merFreezeBill.setMerId(storeOrder.getMerId())
                .setOrderId(storeOrder.getId())
                .setAmountFrozen(price)
                .setFrozen(0);
        save(merFreezeBill);
    }

}
